package cn.beforedark.yygh.hosp.service.impl;

import cn.beforedark.yygh.cmn.client.DictFeignClient;
import cn.beforedark.yygh.common.exception.YyghException;
import cn.beforedark.yygh.dto.hosp.HospitalQueryDto;
import cn.beforedark.yygh.hosp.repository.HospitalRepository;
import cn.beforedark.yygh.hosp.service.HospitalService;
import cn.beforedark.yygh.model.hosp.Hospital;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;


    @Override
    public void save(Map<String, Object> map) {
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(map), Hospital.class);
        String hoscode = hospital.getHoscode();
        Hospital byHoscode = hospitalRepository.findByHoscode(hoscode);
        if (byHoscode == null) {
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            hospital.setId(byHoscode.getId());
            hospital.setCreateTime(byHoscode.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setStatus(byHoscode.getStatus());
            hospital.setIsDeleted(byHoscode.getIsDeleted());
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }


    @Override
    public Page<Hospital> getHosptialPage(Integer pageNum, Integer pageSize, HospitalQueryDto dto) {

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(dto, hospital);

        // 创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() // 构建对象
                // .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // 所有字段模糊查询？？
                .withMatcher("hosname", ExampleMatcher.GenericPropertyMatchers.contains()) // 改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); // 改变默认大小写忽略方式：忽略大小写

        Example<Hospital> example = Example.of(hospital, matcher);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by("createTime").ascending());
        Page<Hospital> result = hospitalRepository.findAll(example, pageRequest);

        result.getContent().stream().forEach(item -> {
            this.packageHospital(item);
        });
        return result;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        if (status == 0 || status == 1) {
            Hospital hospital = hospitalRepository.findById(id).orElseThrow(() -> new YyghException("不存在该医院"));
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getDetailById(String id) {
        return hospitalRepository.findById(id).orElseThrow(() -> new YyghException("不存在该医院"));
    }

    @Override
    public List<Hospital> findByName(String hosname) {
        return hospitalRepository.findByHosnameLike(hosname);
    }

    @Override
    public Hospital getHospitalDetail(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        this.packageHospital(hospital);
        return hospital;
    }


    private void packageHospital(Hospital hospital) {
        String hostype = hospital.getHostype();

        String provinceCode = hospital.getProvinceCode();
        String cityCode = hospital.getCityCode();
        String districtCode = hospital.getDistrictCode();

        String provinceAddress = dictFeignClient.getNameByValue(Long.parseLong(provinceCode));
        String cityAddress = dictFeignClient.getNameByValue(Long.parseLong(cityCode));
        String districtAddress = dictFeignClient.getNameByValue(Long.parseLong(districtCode));

        String level = dictFeignClient.getNameByDictCode("Hostype", Long.parseLong(hostype));

        hospital.getParam().put("hostypeString", level);
        hospital.getParam().put("fullAddress",
                provinceAddress + cityAddress + districtAddress + hospital.getAddress());
    }
}
